package io.file;

import framework.Testable;
import utils.IOUtils;
import utils.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;

/**
 * Created by shane on 2018/5/21.
 */
public class TextFile extends ArrayList<String> {

    public TextFile(String filename, String splitter) {
        super(Arrays.asList(read(filename).split(splitter)));
        // Regular expression split() often leaves an empty
        // String at the first position

        if (size() > 0 && get(0).equals("")) {
            remove(0);
        }
    }

    public TextFile(String filename) {
        this(filename, "\n");
    }

    public static String read(String filename) {
        StringBuilder sb = new StringBuilder();
        BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader(new File(filename).getAbsolutePath()));
            String s;
            while((s = in.readLine()) != null) {
                sb.append(s);
                sb.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(in);
        }

        return sb.toString();
    }

    public static void write(String filename, String text) {
        try {
            PrintWriter out = new PrintWriter(new File(filename).getAbsolutePath());
            out.print(text);
            IOUtils.close(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void write(String filename) {
        try {
            PrintWriter out = new PrintWriter(new File(filename).getAbsolutePath());
            for (String item : this) {
                out.println(item);
            }
            IOUtils.close(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void test() {
        String fileContent = read(Testable.DEFAULT_INPUT_FILE);
        write(Testable.DEFAULT_OUTPUT_FILE, fileContent);

        TextFile textFile = new TextFile(Testable.DEFAULT_INPUT_FILE);
        textFile.write(Testable.DEFAULT_TEMP_FILE);

        TreeSet<String> words = new TreeSet<>(new TextFile(Testable.DEFAULT_INPUT_FILE, "\\W+"));
        Log.v(words.headSet("a"));
        Log.v(words);
    }
}
